<script setup lang="ts">
  import Player from 'xgplayer';
  import { ElMessage } from 'element-plus';
  import { ref, watch } from 'vue';

  let props = defineProps({
    openBullet: {
      type: Boolean,
      required: false,
      default: true,
    },
    url: {
      type: String,
      required: true,
    },
  });

  const emit = defineEmits<(e: 'update:openBullet', value: boolean) => void>();

  let player: Player;
  const count = ref(1);
  const msg = ref<string>('');
  const isClick = ref<boolean>(false);
  const isOpenBullet = ref<boolean>(props.openBullet);

  const inputFocus = () => {
    const commentInput: any = document.getElementById('commentInput');
    commentInput.focus();
  };

  const addCommentStyle = (style: string) => {
    document.getElementById('player-comment-container')!.style.visibility = style;
    document.getElementById('bulletSet')!.style.color = isOpenBullet.value ? 'red' : '#ffffff';
  };

  const sendMsg = () => {
    const fullscreen = player.fullscreen;
    const commentInput: any = document.getElementById('commentInput');
    const inputValue = commentInput.value;
    const content = msg.value;
    commentInput.value = '';

    sendComment(!fullscreen ? content : inputValue);
  };

  const sendComment = (msgComment: string) => {
    if (!isOpenBullet.value) {
      ElMessage.error('你未打开弹幕，是否先打开弹幕');
      return;
    }
    const currentTime = player.currentTime * 1000;
    count.value++;
    player?.danmu?.sendComment({
      duration: 5000,
      id: count.value,
      start: currentTime,
      txt: msgComment,
      style: {
        color: '#ff9500',
        fontSize: '20px',
        fontWeight: 600,
        backgroundColor: 'rgba(255, 255, 255, 0.1)',
      },
    });
  };

  const addContent = () => {
    // 获取目标区域element
    const element = document.getElementsByClassName('xgplayer-placeholder')[0];
    // 添加样式
    element.setAttribute('style', 'display:flex;align-items:center;justify-content:center;');

    // 创建发送弹幕区域的div
    const div = document.createElement('div');
    div.setAttribute('id', 'player-comment-container');
    // 初始化不用展示
    div.setAttribute(
      'style',
      'visibility:hidden;display:flex;align-items:center;justify-content:center;',
    );

    const tit = document.createElement('span');
    tit.setAttribute('style', 'color:' + 'red' + ';padding: 0 30px;' + 'cursor: pointer;');
    tit.setAttribute('id', 'bulletSet');

    const titTxt = document.createTextNode('弹');
    tit.appendChild(titTxt);

    tit.addEventListener('mousedown', () => {
      changeBullet();
      document.getElementById('bulletSet')!.style.color = isOpenBullet.value ? 'red' : '#ffffff';
    });

    const input = document.createElement('input');
    input.setAttribute(
      'style',
      'height: 30px;width: 250px;' +
        'border-radius: 5px 0 0 5px;padding: 0 10px;outline: none;font-size: 10px;',
    );
    input.setAttribute('placeholder', '善语结善缘，恶语伤人心');
    input.setAttribute('id', 'commentInput');
    input.setAttribute('autocomplete', 'off');
    input.setAttribute('value', '');

    input.addEventListener('mousedown', () => {
      document.onmousemove = () => {
        inputFocus();
      };
      isClick.value = false;
    });
    input.addEventListener(
      'keyup',
      event => {
        const keyName = event.key;
        if (keyName === 'Enter') {
          sendMsg();
        }
      },
      false,
    );

    element.addEventListener('mousedown', () => {
      if (isClick.value) {
        document.onmousemove = () => {};
      }
      isClick.value = true;
    });

    const btn = document.createElement('button');
    btn.setAttribute(
      'style',
      'height: 30px;' +
        'border-radius: 0 5px 5px 0;padding: 0 10px;background-color: cadetblue;cursor: pointer;\n',
    );
    btn.addEventListener('mousedown', sendMsg);

    const btnContent = document.createTextNode('发送');
    btn.appendChild(btnContent);
    div.appendChild(tit);
    div.appendChild(input);
    div.appendChild(btn);
    element.appendChild(div);
  };

  const changeBullet = () => {
    if (isOpenBullet.value) {
      player?.danmu?.stop();
    } else {
      player?.danmu?.start();
    }
    emit('update:openBullet', !isOpenBullet.value);
    isOpenBullet.value = !isOpenBullet.value;
  };

  watch(
    () => props.openBullet,
    () => {
      if (props.openBullet !== isOpenBullet.value) {
        changeBullet();
      }
    },
  );

  watch(
    () => props.url,
    () => {
      player.src = props.url;
    },
  );

  onMounted(() => {
    player = new Player({
      id: 'video-content',
      url: props.url,
      autoplay: false,
      volume: 0.3,
      fluid: true,
      loop: true,
      // poster: '../../assets/lo',
      playbackRate: [0.5, 0.75, 1, 1.5, 2],
      defaultPlaybackRate: 1,
      danmu: {
        panel: true,
        comments: [
          // 弹幕数组
          {
            duration: 10000, // 弹幕持续显示时间,毫秒(最低为5000毫秒)
            id: '1', // 弹幕id，需唯一
            start: 3000, // 弹幕出现时间，毫秒
            prior: true, // 该条弹幕优先显示，默认false
            color: true, // 该条弹幕为彩色弹幕，默认false
            txt: '长弹幕长弹幕长弹幕长弹幕长弹幕长弹幕长弹幕长弹幕长弹幕长弹幕', // 弹幕文字内容
            style: {
              // 弹幕自定义样式
              color: '#5fd5d5',
              fontSize: '20px',
              fontWeight: 600,
            },
            mode: 'scroll', // 显示模式，top顶部居中，bottom底部居中，scroll滚动，默认为scroll
          },
        ],
        area: {
          // 弹幕显示区域
          start: 0, // 区域顶部到播放器顶部所占播放器高度的比例
          end: 1, // 区域底部到播放器顶部所占播放器高度的比例
        },
        closeDefaultBtn: true, // 开启此项后不使用默认提供的弹幕开关，默认使用西瓜播放器提供的开关
        defaultOff: !props.openBullet, // 开启此项后弹幕不会初始化，默认初始化弹幕
      },
      errorTips: `请<span>刷新</span>试试`,
    });

    addContent();

    player.on('requestFullscreen', function () {
      addCommentStyle('');
    });

    player.on('exitFullscreen', function () {
      addCommentStyle('hidden');
    });
  });

  onBeforeUnmount(() => {
    player.off('exitFullscreen', function () {
      addCommentStyle('hidden');
    });
    player.off('requestFullscreen', function () {
      addCommentStyle('');
    });
  });

  defineExpose({
    sendComment,
  });
</script>

<template>
  <div class="video-container">
    <div id="video-content"></div>
  </div>
</template>

<style scoped lang="scss">
  .video-container {
    width: 100%;
    height: 100%;
  }

  #video-content {
    background-color: white;
  }
</style>
